package com.example.cruds.controller;



import cn.hutool.core.io.FileUtil;

import com.example.cruds.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class QgFileController {
//    @Value("${ip:localhost}") 这个是本地的
    @Value("${ip:43.142.69.6}")

    String ip;

    @Value("${server.port}")
    String port;

    private static final String ROOT_PATH=System.getProperty("user.dir")+File.separator+"files";
@PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException{
        String originFilename= file.getOriginalFilename();
        String mainName= FileUtil.mainName(originFilename);
        String extName=FileUtil.extName(originFilename);
        if(!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);
        }
        if(FileUtil.exist(ROOT_PATH+File.separator+originFilename)){
            originFilename=System.currentTimeMillis()+"_"+mainName+"."+extName;
        }
        File saveFile=new File(ROOT_PATH+File.separator+originFilename);
        file.transferTo(saveFile);
        String url="http://"+ip+":"+port+"/file/download/"+originFilename;
        return Result.success(url);
    }


    @GetMapping("/download/{filename}")
    public void download(@PathVariable String filename,HttpServletResponse response) throws IOException {
//        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); // 附件下载
        //response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(filename, "UTF-8")); // 预览
        String filePath=ROOT_PATH+File.separator+filename;
        if(!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes=FileUtil.readBytes(filePath);
        ServletOutputStream outputStream=response.getOutputStream();
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}